﻿using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneSwiter : MonoBehaviour
{
    protected AsyncOperation asyn;
    protected bool m_HasComplatedAtSave = false;
    protected SceneLoadingPanel m_LoadingPanel;
    private void Awake()
    {
    }

    virtual protected void Start()
    {

        if (m_LoadingPanel)
            return;
        var canvas = UtilsUnity.GetCanvas();
        var loadPanel = Resources.Load("Prefabs/UI/SceneLoadingPanel") as GameObject;
        var panelObj = Instantiate(loadPanel);

        if (panelObj && canvas)
        {
            panelObj.transform.SetParent(canvas.transform);
            panelObj.transform.localPosition = Vector3.zero;
            panelObj.transform.localScale = Vector3.one;

            panelObj.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width, Screen.height);
            m_LoadingPanel = panelObj.GetComponent<SceneLoadingPanel>();
            if (m_LoadingPanel)
                m_LoadingPanel.gameObject.SetActive(false);
        }
    }

    protected float theMinumeStayTime = 0.6f;
    protected float theMinumeStayTimeCount = 0f;
    protected int processNow = 0;
    // Update is called once per frame
    void Update()
    {
        if (asyn != null)
        {
            var process = (asyn.progress * 100);
            if (process >= 90)
                process = 100;
            if (processNow < process)
                processNow++;
            if (m_LoadingPanel)
                m_LoadingPanel.process = processNow;


            theMinumeStayTimeCount += Time.unscaledDeltaTime;
            if (theMinumeStayTimeCount > theMinumeStayTime && processNow >= 100)
            {
                Time.timeScale = 1;
                asyn.allowSceneActivation = true;
            }
        }
    }
    public virtual void switchScene(string scene)
    {
        m_LoadingPanel.gameObject.SetActive(true);
        m_LoadingPanel.StartLoad();
        asyn = SceneManager.LoadSceneAsync(scene);
        asyn.allowSceneActivation = false;
        Time.timeScale = 0;
    }
}
